using System.Globalization;
using System.Windows.Data;
using System.Windows.Media;

namespace DocumentCreationSystem.Converters
{
    /// <summary>
    /// 十六进制字符串到颜色的转换器
    /// </summary>
    public class HexToColorConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is string hexString && !string.IsNullOrEmpty(hexString))
            {
                try
                {
                    // 确保以#开头
                    if (!hexString.StartsWith("#"))
                        hexString = "#" + hexString;

                    return (Color)ColorConverter.ConvertFromString(hexString);
                }
                catch
                {
                    // 如果转换失败，返回默认颜色
                    return Colors.Blue;
                }
            }

            return Colors.Blue;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is Color color)
            {
                return $"#{color.R:X2}{color.G:X2}{color.B:X2}";
            }

            return "#0000FF";
        }
    }
}
